package com.liwen.service.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : li.rui
 * @time : 2017-05-08 13:39
 * @desc : RedisConfig
 */
@Configuration
public class RedisConfig extends AppConfig {

    /**
     * 获取前缀
     *
     * @return
     */
    @Override
    protected String prefix() {
        return "redis.";
    }

    @Autowired
    @Bean(name = "jedisPool")
    public JedisPool jedis(JedisPoolConfig config) {
        return new JedisPool(config, getStr("host"), getInt("port"), getInt("timeout"), getStr("password"));
    }

    @Autowired
    @Bean(name = "shareJedisPool")
    public ShardedJedisPool shareJedis(JedisPoolConfig config) {
        log("shareJedisPool.init.start");
        JedisShardInfo shardInfo = new JedisShardInfo(getStr("host"), getInt("port"), getInt("timeout"));
        shardInfo.setPassword(getStr("password"));
        List<JedisShardInfo> list = new ArrayList<>();
        list.add(shardInfo);
        log("shareJedisPool.init.end");
        return new ShardedJedisPool(config, list);
    }

    @Bean(name = "jedisPoolConfig")
    public JedisPoolConfig jedisPoolConfig() {
        log("jedisPoolConfig.init.start");
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(getInt("pool.max-total"));
        config.setMaxIdle(getInt("pool.max-idle"));
        config.setMinIdle(getInt("pool.min-idle"));
        config.setMaxWaitMillis(getLong("pool.max-wait-millis"));
        config.setTestOnBorrow(getBool("pool.test-on-borrow"));
        config.setTestOnReturn(getBool("pool.test-on-return"));
        log("jedisPoolConfig.init.end");
        return config;
    }
}
